package au.edu.anu.club.cs.sql;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TeamDataSource {
	
	private SQLiteDatabase db;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.TEAMID,
									MySQLiteHelper.TEAMNAME,
									MySQLiteHelper.TEAMLOGO,
									MySQLiteHelper.TIMEREGISTERED};
	
	public TeamDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
		db = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public boolean createTeam(long TeamID, String TeamName, String TeamLogo, long TimeRegistered) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.TEAMID, TeamID);
		values.put(MySQLiteHelper.TEAMNAME, TeamName);
		values.put(MySQLiteHelper.TEAMLOGO, TeamLogo);
		values.put(MySQLiteHelper.TIMEREGISTERED, TimeRegistered);
		
		long insertID = db.insert(MySQLiteHelper.TABLE_ANUIB_TEAMS, null, values);
		//Cursor cursor = db.query(MySQLiteHelper.TABLE_ANUIB_TEAMS, allColumns,
		//		MySQLiteHelper.TEAMID + " = " + insertID, null, null, null, null);
		//Team newTeam = cursorToTeam(cursor);
		//cursor.close();
		return insertID != -1; //newTeam;
	}
	
	public List<Team> getAllTeams() {
		List<Team> teams = new ArrayList<Team>();
		
		Cursor cursor = db.query(MySQLiteHelper.TABLE_ANUIB_TEAMS,
				allColumns, null, null, null, null, "TeamID ASC");
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Team team = cursorToTeam(cursor);
			teams.add(team);
			cursor.moveToNext();
		}
		cursor.close();
		return teams;
	}
	
	private Team cursorToTeam(Cursor cursor) {
		Team team = new Team();
		team.setTeamID(cursor.getLong(0));
		team.setTeamName(cursor.getString(1));
		team.setTeamLogo(cursor.getString(2));
		team.setTimeRegistered(cursor.getLong(3));
		return team;
	}
}
